/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 财务管理APP充值金额查询
 *  */

import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { ProFormText } from '@ant-design/pro-form';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbRemarksModal from '@/components/KbRemarksModal';
import KbInvoiceModal from '@/components/_pages/Finance/components/KbInvoiceModal';
import { getData } from '@/services/Financial';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Popover } from 'antd';
import type { HTTableListItem, CzTableListItem } from './index.d';
import styles from './index.less';

const NoticeVerify: React.FC = () => {
  const rules = [
    {
      required: true,
      message: '请输入快递员或者快宝驿站账号',
    },
    {
      pattern: new RegExp(/^[1-9]\d*$/, 'g'),
      message: '账号为数字',
      warningOnly: true,
    },
  ];

  const actionRef = useRef<ActionType>();
  const [record, setRecord] = useState<any>({});
  const [dataSource, setDataSource] = useState<CzTableListItem[]>([]);
  const [visible, setVisible] = useState<boolean>(false);

  const handleOption = (data: any) => {
    setRecord(data);
    setVisible(true);
  };

  const czColumns: ProColumns<CzTableListItem>[] = [
    {
      title: 'APP类型',
      dataIndex: 'app_name',
      width: 100,
      align: 'center',
      search: false,
    },
    {
      title: '总充值金额（元）',
      dataIndex: 'total_recharge_amount',
      width: 130,
      align: 'center',
      search: false,
    },
    {
      title: '剩余未开票金额（元）',
      dataIndex: 'unbilled_amount',
      width: 130,
      align: 'center',
      search: false,
    },
    {
      title: '已开票金额（元）',
      dataIndex: 'billed_amount',
      width: 120,
      align: 'center',
      search: false,
    },
    {
      title: '历史开票抬头',
      dataIndex: 'invoice_title',
      align: 'center',
      width: 150,
      search: false,
      ellipsis: true,
      render: (_, record_) => {
        const { invoice_title = [] } = record_;
        return invoice_title.map((item) => (
          <Popover key={item} content={item} trigger='hover'>
            <div className={styles.main__ellipsis}>{item}</div>
          </Popover>
        ));
      },
    },
    {
      title: '操作',
      dataIndex: 'app_name',
      align: 'center',
      width: 80,
      search: false,
      render: (_, record_) => {
        const { id = '0', kb_id = '0' } = record_;
        console.log(kb_id ? '1' : '2');
        return kb_id != '0' ? (
          <KbInvoiceModal key={id} actionRef={actionRef} queryData={{ id, kb_id }}>
            <a>添加开票信息</a>
          </KbInvoiceModal>
        ) : null;
      },
    },
  ];
  const columns: ProColumns<HTTableListItem>[] = [
    {
      title: '',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            label='账号'
            width='lg'
            name='phone'
            placeholder='请输入快递员或者快宝驿站账号'
            rules={rules}
          />
        );
      },
    },
    {
      title: 'APP类型',
      dataIndex: 'app_name',
      align: 'center',
      search: false,
    },
    {
      title: '充值月份',
      dataIndex: 'date',
      align: 'center',
      search: false,
    },
    {
      title: '充值金额(元)',
      dataIndex: 'amount',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record_) => {
        const { kb_id, remark_status } = record_;
        return kb_id > 0 ? (
          <a key={kb_id + remark_status} onClick={handleOption.bind(null, record_)}>
            {remark_status == '0' ? '添加备注' : '查看'}
          </a>
        ) : (
          '-'
        );
      },
    },
  ];

  const fetchTableList = async (params: any): Promise<any> => {
    const { phone } = params;
    const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if (!phone) {
      return {};
    }
    if (!reg.test(phone)) {
      message.error('请输入正确账号');
      return {};
    }
    const { code, data, msg } = await getData(params);
    if (code == 0) {
      setDataSource(data.account);
      return { data: data.detail };
    } else {
      message.error(msg);
      return {};
    }
  };

  return (
    <PageContainer className={styles.main} title='APP充值金额查询'>
      <DragTable>
        <ProTable<HTTableListItem>
          cardProps={{
            title: '充值记录',
          }}
          className='kb-pro-table'
          actionRef={actionRef}
          pagination={false}
          rowKey={(d) => d.kb_id + d.remark_date}
          manualRequest
          request={fetchTableList}
          columns={columns}
          options={false}
          scroll={{ x: 640 }}
          tableExtraRender={() => (
            <ProTable<CzTableListItem>
              className='kb-pro-table'
              pagination={false}
              rowKey='app_name'
              manualRequest
              dataSource={dataSource}
              columns={czColumns}
              options={false}
              scroll={{ x: 640 }}
              search={false}
            />
          )}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender: (_, { form }) => [
              <Button
                onClick={() => {
                  actionRef.current?.reset();
                  setDataSource([]);
                }}
                key='reset'
              >
                重置
              </Button>,
              <Button onClick={() => form?.submit()} type='primary' key='search'>
                查询
              </Button>,
            ],
          }}
        />
      </DragTable>
      <KbRemarksModal
        modalTitle='添加备注'
        required
        visible={visible}
        setVisible={setVisible}
        formatDataMap={{
          label: 'operate_name',
          remark: 'remark',
          user: 'operate_mobile',
          time: 'create_time',
        }}
        api='/FinanceAppRecharge/addRemark'
        formData={{ kb_id: record.kb_id, remark_date: record.remark_date }}
        listApi='/FinanceAppRecharge/getRemarkList'
        listFormData={{
          kb_id: record.kb_id,
          remark_date: record.remark_date,
          kb_type: record.kb_type,
        }}
      ></KbRemarksModal>
    </PageContainer>
  );
};

export default NoticeVerify;
